package org.funtester.performance.books.chapter05.section4;

import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import org.funtester.performance.books.chapter05.sectioin3.NettyWebSocketClient;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * Netty-WebSocket客户端保活在性能测试中实践
 */
public class NettyWebsocketKeepAlive {

    public static void main(String[] args) throws URISyntaxException, InterruptedException {
        String url = "ws://localhost:12345/websocket";// 服务端地址
        URI uri = new URI(url);// 转换为URI
        List<ChannelPromise> promises = new ArrayList<>();// 存储连接的promise
        for (int i = 0; i < 10000; i++) {
            NettyWebSocketClient nettyWebSocketClient = new NettyWebSocketClient(uri);// 创建客户端
            ChannelPromise connect = nettyWebSocketClient.connect();// 连接
            promises.add(connect);// 存储promise
        }
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(10000);// 10秒发送一次心跳
                    NettyWebSocketClient.channels.writeAndFlush(new PingWebSocketFrame()).sync();// 发送订阅消息,阻塞等待所有消息发送完成
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();// 启动心跳线程
        for (int i = 0; i < promises.size(); i++) {
            promises.get(i);// 等待 WebSocket 握手成功
        }
        // 下面开始编写性能测试用例
    }

}
